﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.ProOrderCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.ProOrderCommandHandlers
{
    public class UptProOrderCommandHandlers:IRequestHandler<UptProOrderCommand,int>
    {

        private readonly IProOrderRepository _PRoOrder;

        private readonly IProOrderDetailRepository _proOrderDetail;
        private readonly IMapper _mapper;
        ISqlSugarClient db;

        public UptProOrderCommandHandlers(IProOrderRepository PRoOrder, IProOrderDetailRepository proOrderDetail, IMapper mapper, ISqlSugarClient sqlSugarClient)
        {
            _PRoOrder = PRoOrder;
            _proOrderDetail = proOrderDetail;
            _mapper = mapper;
            db = sqlSugarClient;
        }

        public async Task<int> Handle(UptProOrderCommand request, CancellationToken cancellationToken)
        {

            db.Ado.BeginTran();
            try
            {
                var res = _mapper.Map<ProduceOrders>(request.Dto);
                await _PRoOrder.UpdAsync(res);

                var result = (await _proOrderDetail.GetAll()).Where(x => x.POId == res.POrderNumber).ToList();
                 var del= await _proOrderDetail.DelRange(result);
                foreach (var item in request.Dto.DetailList)
                {
                    ProduceOrderDetail newDetail = new ProduceOrderDetail()
                    {
                        POId = item.POId,
                        PPId = item.PPId,
                        PCompletionDate = item.PCompletionDate,
                        PDeliveryDate = item.PDeliveryDate,
                        POrderNum = item.POrderNum,
                        ProductionPlansId = item.ProductionPlansId,
                        ProductionType = item.ProductionType,
                        ProductId = item.ProductId,
                        PStartTime = item.PStartTime,
                        AddName = item.AddName,
                        AddTime = item.AddTime,
                        UpdName = item.UpdName,
                        UpdTime = item.UpdTime,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id,
                    };
                    await _proOrderDetail.AddAsync(newDetail);
                }
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {

                db.Ado.RollbackTran();
                throw;
            }


        }
    }
}
